//
//  EventDescriptionByTagsViewController.m
//  SecretRoom
//
//  Created by Sitdhibhong Laokok on 9/4/54 BE.
//  Copyright 2554 App Tree. All rights reserved.
//

#import "EventDescriptionByTagsViewController.h"

#import "Tag.h"

@interface EventDescriptionByTagsViewController ()
- (void)displayTagManagementPage;
@end

@implementation EventDescriptionByTagsViewController

@synthesize context;
@synthesize tagsFetchedController=_tagsFetchedController;
@synthesize tagsConfirmButton;
@synthesize tagList;
@synthesize delegate;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithTags:(NSArray *)initInvitees
{
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {
        self.tagList = [NSMutableArray arrayWithArray:initInvitees];
    }
    
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
} 

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = @"Tags";

    tagList = [[NSMutableArray alloc] init];
    
    self.navigationController.toolbarHidden = NO;
    
    self.navigationItem.rightBarButtonItem = self.tagsConfirmButton;
    
    UIBarButtonItem *tagsSelectorConfirmed = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:@selector(tagsConfirmButtonClicked:)];
    self.navigationItem.rightBarButtonItem = tagsSelectorConfirmed;
    [tagsSelectorConfirmed release];
    
    NSError *error = nil;
    [self.tagsFetchedController performFetch:&error];
    if (error != nil) {
        NSLog(@"%s Error while fetching tag list: %@", __PRETTY_FUNCTION__, [error localizedDescription]);
    } else {
        [self.tableView reloadData];
    }
    
    UIBarButtonItem *displayTagManagementPageButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(displayTagManagementPage)];
    self.toolbarItems = [NSArray arrayWithObjects:displayTagManagementPageButton, nil];
    self.navigationController.toolbarHidden = NO;
    
    [displayTagManagementPageButton release];

}

- (void)viewDidUnload
{
    [self setTagsConfirmButton:nil];
    [self setTagList:nil];
    [self setTagsFetchedController:nil];
    [self setContext:nil];
    [self setTagList:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[[self.tagsFetchedController sections] lastObject] numberOfObjects];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    Tag *tag = [self.tagsFetchedController objectAtIndexPath:indexPath];
    if ([self.tagList indexOfObject:tag] != NSNotFound) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    cell.textLabel.text = tag.tagName;
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Tag *tag = [self.tagsFetchedController objectAtIndexPath:indexPath];
    if ([self.tagList indexOfObject:tag] != NSNotFound) {
        [self.tagList addObject:tag];
        [self.tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
    } else {
        [self.tagList removeObject:tag];
        [self.tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone;
    }
}

- (void)dealloc {
    [tagsConfirmButton release];
    [tagList release];
    [tagsFetchedController release];
    [context release];
    [super dealloc];
}

- (IBAction)tagsConfirmButtonClicked:(id)sender 
{
    NSLog(@"Tags confirmed");
    if (self.delegate != nil && [self.delegate respondsToSelector:@selector(setTagsForThisEvent:)]) {
        [self.delegate setTagsForThisEvent:self.tagList];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - class override

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    self.tableView.editing = NO;
}

#pragma mark - Class Accessor Override

- (NSFetchedResultsController *)tagsFetchedController
{
    if (_tagsFetchedController != nil) {
        return _tagsFetchedController;
    }
    
    NSFetchRequest *allTagsFetchRequest = [[NSFetchRequest alloc] init];
    allTagsFetchRequest.entity = [NSEntityDescription entityForName:@"Tag" inManagedObjectContext:[[SRConnectionControlCenter sharedInstance] manageObjectContext]];
    allTagsFetchRequest.sortDescriptors = [NSArray arrayWithObjects:[NSSortDescriptor sortDescriptorWithKey:@"remoteCount" ascending:YES], nil];
    allTagsFetchRequest.predicate = nil;

    NSFetchedResultsController *fetchedTagResultController = [[NSFetchedResultsController alloc] initWithFetchRequest:allTagsFetchRequest managedObjectContext:[[SRConnectionControlCenter sharedInstance] manageObjectContext] sectionNameKeyPath:nil cacheName:@"tags"];
    
    self.tagsFetchedController = fetchedTagResultController;
    
    [allTagsFetchRequest release];
    [fetchedTagResultController release];
    
    return _tagsFetchedController;
}

#pragma mark - Secret Method 
- (void)displayTagManagementPage
{
    
}

@end
